import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import { WaterTest } from '@app/db/entity/WaterTest';
import { FindOptionsWhere, LessThan } from 'typeorm';
import { AlicloudService } from '@app/alicloud';
import { CacheService } from '@app/cache';
import { DeviceService } from '../device/device.service';
import { DEVICE_CTR_ORDER } from 'constant/DEVICE_CTR_ORDER';

@Injectable()
export class WaterTestService {
    constructor(
        private readonly db:DbService,
        private readonly cache:CacheService,
        private readonly alicloud:AlicloudService,
        private readonly deivce:DeviceService,

    ){}

    async test(deviceId:number, userId:number) {
        const key = 'test.' + deviceId
        const had = await this.cache.get(key)
        //if(had != null) return null


        let lockKey = 'test.lock.' + deviceId
        const lock = await this.cache.set(lockKey, '', 10, 'NX')
        if(!lock) return null
        const device = await this.db.device.findOne({id : deviceId}, {userId : true, deviceTypeId : true, aliSecret : true})
        
        if(!device || device.userId != userId) return null

        const deviceType = await this.db.deviceType.findOne({id : device.deviceTypeId}, {aliProduct : true})
        if(!deviceType) return null

        const r = await this.db.waterTest.insert({
            userId,
            deviceId,
            createTime : Math.floor(Date.now() / 1000),
            //data : []
        })


        console.log(r)

        if(r != null && r.affectedRows > 0) {
            this.cache.set(key, r.rows[0].id)
            const res = await this.deivce.pub(deviceId, deviceType.aliProduct, {
                "v":"ss_1",
                cmd : DEVICE_CTR_ORDER.SET_CHECK_STEP,
                param : "1",
                port : '0',
                "goal": "0",
                childPort: "",
                msgId : String(r.rows[0].id),
            })

            console.log(res)
        }
        
    }
    
    async page(query:Pagination, userId:number) {
        let where:FindOptionsWhere<WaterTest> = { userId }
        const lastId = query.lastKey || 0
        const pageSize = query.pageSize || 20

        if(lastId > 0) {
            where.id = LessThan(lastId)
        }

        let rows:WaterTest[] = await this.db.waterTest.getRepository().find({
            select : {id : true, deviceId : true, status : true, result : true, createTime : true, endTime : true},
            where,
            skip : 0, 
            take : pageSize, 
            order : {id : 'DESC'}
        })

        return rows
    }

    async data(id:number, userId:number) {
        const r = await this.db.waterTest.findOne({id : id}, {userId : true, data : true})
        if(!r || r.userId != userId) return null

        return r.data
    }
}
